package cn.buttheway.moodmusicdiary.adapters;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import cn.buttheway.moodmusicdiary.R;
import cn.buttheway.moodmusicdiary.models.MoodEntry;

public class MoodHistoryAdapter extends RecyclerView.Adapter<MoodHistoryAdapter.MoodViewHolder> {

    private List<MoodEntry> moodEntries;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

    public MoodHistoryAdapter(List<MoodEntry> moodEntries) {
        this.moodEntries = moodEntries;
    }

    @NonNull
    @Override
    public MoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_mood_history, parent, false);
        return new MoodViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MoodViewHolder holder, int position) {
        MoodEntry moodEntry = moodEntries.get(position);
        holder.tvDate.setText(dateFormat.format(moodEntry.getDate()));
        holder.tvMoodText.setText(moodEntry.getMoodText());
        holder.tvSentiment.setText(moodEntry.getSentiment());
        holder.tvSong.setText(moodEntry.getSong().getTitle() + " - " + moodEntry.getSong().getArtist());
    }

    @Override
    public int getItemCount() {
        return moodEntries.size();
    }

    public void sortByDate() {
        Collections.sort(moodEntries, (m1, m2) -> m2.getDate().compareTo(m1.getDate()));
        notifyDataSetChanged();
    }

    public void sortBySentiment() {
        Collections.sort(moodEntries, (m1, m2) -> m1.getSentiment().compareTo(m2.getSentiment()));
        notifyDataSetChanged();
    }

    static class MoodViewHolder extends RecyclerView.ViewHolder {
        TextView tvDate, tvMoodText, tvSentiment, tvSong;

        MoodViewHolder(View itemView) {
            super(itemView);
            tvDate = itemView.findViewById(R.id.tvDate);
            tvMoodText = itemView.findViewById(R.id.tvMoodText);
            tvSentiment = itemView.findViewById(R.id.tvSentiment);
            tvSong = itemView.findViewById(R.id.tvSong);
        }
    }
}